package com.szboanda.parser;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author ：zhangsheng
 * @date ：Created in 2020/2/22 14:16
 * @description：解析器异常
 * @modified By：
 * @version: 1.0$
 */
public class SqlParserException extends RuntimeException {

    /**
     * 序列化号
     */
    private static final long serialVersionUID = 1L;

    /**
     * 异常编码
     */
    private String code;

    /**
     * 获取异常编码
     *
     * @return
     */
    public String getCode() {
        return code;
    }

    /**
     * 设置异常编码
     *
     * @param code
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * 构造一个不带参数的异常实例
     *
     */
    public SqlParserException() {
        super();
    }

    /**
     * 使用指定消息构造一个异常实例
     *
     * @param message
     */
    public SqlParserException(String message) {
        super(message);
    }

    /**
     * 使用指定消息构造和code一个异常实例
     *
     * @param message
     * @param code
     */
    public SqlParserException(String message, String code) {
        super(message);
        this.code = code;
    }

    /**
     * 使用指定的cause构造一个异常实例
     *
     * @param cause
     */
    public SqlParserException(Throwable cause) {
        super(cause);
    }

    /**
     * 使用指定消息和cause构造一个异常实例
     *
     * @param message
     * @param cause
     */
    public SqlParserException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * 使用指定消息构造和code和cause一个异常实例
     *
     * @param message
     * @param code
     */
    public SqlParserException(String message, Throwable cause, String code) {
        super(message, cause);
        this.code = code;
    }

    /**
     * 转换异常
     *
     * @param t
     * @return
     */
    public static RuntimeException processException(Throwable t) {
        if (t instanceof RuntimeException) {
            return (RuntimeException) t;
        } else {
            return new SqlParserException(t);
        }
    }

    /**
     * 把异常消息写到字符串
     * @return
     */
    public String writeToString() {
        String message = "";
        StringWriter stringWriter = null;
        PrintWriter printWriter = null;
        try {
            stringWriter = new StringWriter();
            printWriter = new PrintWriter(stringWriter);
            this.printStackTrace(printWriter);
            message = stringWriter.toString();
        } finally {
            printWriter.close();
            try{
                stringWriter.close();
            }catch (IOException io) {
            }

        }
        return message;
    }

}
